package com.neo.office.server.service.Impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.neo.office.server.domain.entity.Menu;
import com.neo.office.server.mapper.MenuMapper;
import com.neo.office.server.service.MenuService;
import com.neo.office.server.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 根据用户ID查询菜单列表
     * Redis缓存数据
     * @return
     */
    @Override
    public List<Menu> getMenusByUserId() {
        Integer userId = UserUtils.getCurrentUser().getId();
        ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
        //从redis获取菜单数据
        List<Menu> menus = (List<Menu>) valueOperations.get("menu_" + userId);
        //如果为空，去数据库取
        if (CollectionUtils.isEmpty(menus)){
            menus = menuMapper.getMenusByUserId(userId);
            //将数据设置到Redis中
            valueOperations.set("menu_" + userId,menus);
        }
        return menus;
    }

    /**
     * 根据角色获取菜单列表
     * @return
     */
    @Override
    public List<Menu> getMenusWithRole() {
        return menuMapper.getMenusWithRole();
    }

    /**
     * 查询权限菜单
     * @return
     */
    @Override
    public List<Menu> getMenuOfPermission() {
        return menuMapper.getMenuOfPermission();
    }
}
